<?php
if (!defined('IN_CORE')) die('禁止访问!');
define('CORE_VERSION','2.0.0');						//core核心版本
header("Content-Type:text/html;charset=utf-8");		//设置系统的输出字符为utf-8
date_default_timezone_set('PRC');					//设置时区为中国

define('DS',DIRECTORY_SEPARATOR);
if (!defined('APP_NAME')) define('APP_NAME','home');
define('CORE_PATH',dirname(__FILE__));		//物理框架根目录
define('ROOT_PATH',getcwd());				//物理程序根目录
define('APP_PATH',ROOT_PATH.DS.APP_NAME);	//物理当前应用
class core{
	public static $core_uri		= 'index/index';
	public static $action 		= 'index';
	public static $method 		= 'index';
	public static $config		= null;
	public static function run() {
		self::startDebug();
		self::init();
		self::setLoad();
		self::router();
		self::control();
		self::endDebug();
	}
	public static function startDebug(){
		//设置debug
		if(defined('DEBUG') && DEBUG==true){
			$GLOBALS['debug']=1;                 //初例化开启debug
			error_reporting(E_ALL ^ E_NOTICE);   //输出除了注意的所有错误报告
			include CORE_PATH.DS.'debug.class.php'; 			 //包含debug类
			Debug::start();                               //开启脚本计算时间
			set_error_handler(array('Debug', 'Catcher')); //设置捕获系统异常
		}else{
			ini_set('display_errors', 'Off'); 		//屏蔽错误输出
			ini_set('log_errors', 'On');             //开启错误日志，将错误报告写入到日志中
			ini_set('error_log', ROOT_PATH.DS.'runtime'.DS.APP_NAME.DS.'error_log'); //指定错误日志文件
		}
	}
	public static function endDebug(){
		//设置输出Debug模式的信息
		if(defined('DEBUG') && DEBUG==1 && $GLOBALS["debug"]==1){
			Debug::stop();
			Debug::message();
		}
	}
	public static function addmsg($msg='！', $type=0){
		if(defined('DEBUG') && DEBUG==1 && $GLOBALS["debug"]==1){
			Debug::addmsg($msg, $type);
		}
	}
	protected static function init(){
		if(get_magic_quotes_gpc()){
			ini.set('magic_quotes_gpc', 0);
		}
		$config_path='config.class.php';
		if(file_exists($config_path)){
			self::addmsg("<b>载入</b> [config.class.php] 文件", 1);
			require($config_path);
			self::$config = $config;
		}else{
			self::addmsg('<b>没有</b> [config.class.php] 文件', 1);
		}
		//默认框架必须目录，若不存在则自动创建
		$core_dirs=array(
			APP_PATH.DS,
			APP_PATH.DS.'controls'.DS,		//应用控制文件夹
			APP_PATH.DS.'models'.DS,		//应用模型文件夹
			APP_PATH.DS.'views'.DS,			//应用模板文件夹
			ROOT_PATH.DS.'runtime'.DS,
			ROOT_PATH.DS.'runtime'.DS.APP_NAME.DS,					//缓存主目录
			ROOT_PATH.DS.'runtime'.DS.APP_NAME.DS.'comps'.DS,		//模板编译
			ROOT_PATH.DS.'runtime'.DS.APP_NAME.DS.'cache'.DS,		//模板缓存
			ROOT_PATH.DS.'runtime'.DS.APP_NAME.DS.'error_log'.DS,	//错误日志
		);
		self::mkdirs($core_dirs);
		unset($core_dirs);
	}
	protected static function setLoad(){
		//include默认包含路径
		$include_path=get_include_path();							//自带目录 类库
		$include_path.=PATH_SEPARATOR.CORE_PATH;					//核心框架 核心类库 
		$include_path.=PATH_SEPARATOR.CORE_PATH.DS.'Smarty';		//核心框架 smarty类库
		$include_path.=PATH_SEPARATOR.CORE_PATH.DS.'Libs';			//核心框架 smarty类库 
		
		$include_path.=PATH_SEPARATOR.APP_PATH.DS.'controls';		//应用程序 控制器类
		$include_path.=PATH_SEPARATOR.APP_PATH.DS.'models';		//应用程序 自建libs类库

		set_include_path($include_path);							//设置include包含文件所在的所有目录
		spl_autoload_register(array('core','autoLoad'));
	}
	protected static function autoLoad($core_class) {
		$core_class = strtolower($core_class);
		$bool=include($core_class.'.class.php');
		if(!$bool) include($core_class.'.class.php');
		self::addmsg("<b>载入</b> [{$core_class}.class.php] 文件", 1);
	}
	protected static function router(){
		if(isset($_SERVER['PATH_INFO'])) {
			self::$core_uri = $_SERVER['PATH_INFO'];
		}
		if(isset($_SERVER['ORIG_PATH_INFO'])) {
			self::$core_uri = $_SERVER['ORIG_PATH_INFO'];
		}
		if(isset($_SERVER['SCRIPT_URL'])) {
			self::$core_uri = $_SERVER['SCRIPT_URL'];
		}
		self::$core_uri = trim(self::$core_uri,'/');
		$uri_array = explode('/',self::$core_uri);
		$uri_count=count($uri_array);
		//读取路由配置
		//$arr=array('path'=>'get#user/:str','action'=>'index/show');
		$match=false;
		if(isset(self::$config['router'])){
			foreach(self::$config['router'] as $arr){
				$arr['path']=explode('#',$arr['path']);
				$pattern = trim($arr['path'][1], '/');
				$pattern = '/'.str_replace('/', '\/', $pattern).'\/?$/';
				$pattern = str_replace(':str', '([^\/]+)', $pattern);
				$pattern = str_replace(':id', '(\d+)', $pattern);
				$match = preg_match($pattern,self::$core_uri);
				if($match) break;
			}
		}
		if($match){
			//匹配到路由配置时候
			$action=explode('/',$arr['path'][1]);
			$key=$action[0];
			$method=strtolower($arr['path'][0]);
			$arr['action'] = explode('/',$arr['action']);
			self::$action=$arr['action'][0];
			self::$method=$arr['action'][1];
			if($method=='get'){
				$_GET[$key]=$uri_array[1];
			}else{
				$_POST[$key]=$uri_array[1];
			}
		}else{
			//没有路由配置时候
			self::$action = strtolower($uri_array[0] ? $uri_array[0] : 'index');
			self::$method = strtolower(isset($uri_array[1]) ? $uri_array[1] : 'index');
			empty(self::$core_uri) && self::$core_uri='index/index';
			if($uri_count>2){
				if($uri_count%2==0){
					for($i=2;$i<$uri_count;$i+=2){
						$_GET[$uri_array[$i]]=$uri_array[$i+1];
					}
				}else{
					self::show404('URL参数不匹配！');
				}
			}
		}
		//模板文件中所有要的路径，html\css\javascript\image\link等中用到的路径，从WEB服务器的文档根开始
		$spath=rtrim(substr(dirname(str_replace('\\', '/', dirname(__FILE__))), strlen(rtrim($_SERVER["DOCUMENT_ROOT"],DS))), '/\\');
		$GLOBALS['sroot']='/'.$spath.'/';
		$GLOBALS['root']='http://'.$_SERVER['HTTP_HOST'].$GLOBALS['sroot']; //Web服务器根到项目的根
		$GLOBALS['public']=$GLOBALS['sroot'].'public'.'/';        	//全局资源目录
		$GLOBALS['app']=$GLOBALS['root'].APP_NAME.'/';
		$GLOBALS['res']=$GLOBALS['sroot'].APP_NAME.'/views/res/';
		$GLOBALS['url']=$_SERVER['SCRIPT_NAME'].'/';
		$GLOBALS['act']=$_SERVER['SCRIPT_NAME'].'/'.self::$action.'/';
	}
	protected static function control(){
		$class_path = APP_PATH.DS.'controls'.DS.self::$action.'.class.php';
		if(!file_exists($class_path)) 		self::show404("({$class_path}) 类文件不存在!");
		if(!class_exists(self::$action)) 	self::show404("($class_path) 中没有以 {self::$action} 命名的类!");
		if(!method_exists(self::$action,self::$method)) self::show404("($class_path) 中访问的方法不存在!");
		session_start();
		self::addmsg('<b>开启Session会话</b> '.session_id());
		//加载控制类
		$action = self::$action;
		$method = self::$method;
		$core = new $action();
		$core-> $method();
	}
	public static function show404($msg=''){
		if(defined('DEBUG') && DEBUG==1 && $GLOBALS["debug"]==1){
			self::addmsg($msg);
			self::endDebug();
		}else{
			header("HTTP/1.1 404 Not Found");
		}
		exit(1);
	}
	public static function model($name=null){
		// 载入数据库
		if(!is_null($name)){
			$class_path = APP_PATH.DS.'models'.DS.$name.'.class.php';
			if(file_exists($class_path) && class_exists(self::$action) && method_exists(self::$action,self::$method)){
				$model=new $name ($name);
			}
		}else{
			$model=new model();
		}
		return $model;
	}
	public static function cache($path=null){
		is_null($path) && $path='data';
		if ($path=='data') {$path=ROOT_PATH.DS.'runtime'.DS.'data_cache.php';}
		else if ($path=='table') {$path=ROOT_PATH.DS.'runtime'.DS.'table_cache.php';}
		else {$path=ROOT_PATH.DS.'runtime'.DS.$path;}
		self::addmsg("<b>缓存</b> [{$path}] 文件", 1);
		$cache=new NotORM_Cache_Include($path);
		return $cache;
	}
	public static function mkdirs($dirs=null){
		if(is_array($dirs)){
			foreach($dirs as $dir){
				if(!file_exists($dir)){
					if(mkdir($dir,"0755")){
						Debug::addmsg('创建目录'.$dir.'成功');
					}
				}
			}
		}
	}
}
//继承，简化名字
final class c extends core{}